<template>
    <div class="container">
        <Breadcrumb :items="['menu.card', 'menu.member.company']" />
        <a-card :title="$t('menu.member.company')">

            <a-space fill direction="vertical">
                <a-row :gutter="16">
                    <a-col :span="12">
                        <a-space fill>
                            <a-button type="primary" @click="openModal()" shape="round">
                                <template #icon><icon-plus /></template>
                                添加单位
                            </a-button>

                            <a-button @click="openKfModal()" shape="round">
                               
                                单位客服管理
                            </a-button>
                        </a-space>

                    </a-col>
                    <a-col :flex="1">
                        <a-space align="end" style="justify-content: flex-end;" fill>
                            <a-button shape="circle" @click="fetchData">
                                <template #icon><icon-refresh /></template>
                            </a-button>
                        </a-space>
                    </a-col>
                </a-row>

                <a-table :data="renderData" :loading="loading" :bordered="{ cell: true }" :pagination="pagination"
                    @page-change="onPageChange" @page-size-change="onPageSizeChange">
                    <template #columns>
                        <a-table-column title="ID" data-index="id" :width="80" />
                        <a-table-column title="公司名称" data-index="name" />
                        <a-table-column title="所在城市" data-index="city_name" :width="120" />
                        <a-table-column title="员工数量" data-index="person_total" :width="100" />
                        <a-table-column title="卡批次" data-index="card_total" :width="100" />
                        <a-table-column title="卡片数量" data-index="card_item_total" :width="100" />
                        <a-table-column title="领卡数量" data-index="card_user_total" :width="100" />
                        <a-table-column title="负责人" data-index="master_name" :width="100" />
                        <a-table-column title="联系电话" data-index="master_phone" :width="150" />
                        <a-table-column title="地址" data-index="address" :width="200" :ellipsis="true" :tooltip="true"/>
                        <a-table-column title="创建时间" data-index="created_at" :width="180" />
                        <a-table-column title="操作" align="center" :width="200" fixed="right">
                            <template #cell="{ record }">
                                <a-space size="mini">
                                    <a-link @click="handleMasterData(record)">
                                        管理账户
                                    </a-link>

                                    <a-link @click="openModal(record)">
                                        编辑
                                    </a-link>

                                    <a-popconfirm position="left" content="确定要删除这个公司吗？" @ok="handleDelete(record.id)">
                                        <a-link>
                                            删除
                                        </a-link>
                                    </a-popconfirm>
                                </a-space>
                            </template>
                        </a-table-column>
                    </template>
                </a-table>
            </a-space>
        </a-card>

        <a-modal v-model:visible="modalVisible" :title="formData.id ? '编辑公司' : '添加公司'" @before-ok="handleSubmit"
            @cancel="closeModal" :width="800">
            <a-form :model="formData" ref="formRef" layout="vertical">
                <a-row :gutter="16">
                    <a-col :span="12">
                        <a-form-item field="name" label="公司名称" :rules="[{ required: true, message: '请输入公司名称' }]">
                            <a-input v-model="formData.name" placeholder="请输入公司名称" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item field="city_id" label="所在城市">
                            <a-select v-model="formData.city_id" placeholder="请选择所在城市" :loading="cityLoading" allow-clear>
                                <a-option v-for="city in cityOptions" :key="city.id" :value="city.id">
                                    {{ city.name }}
                                </a-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row :gutter="16">
                    <a-col :span="12">
                        <a-form-item field="person_total" label="员工数量">
                            <a-input-number v-model="formData.person_total" placeholder="请输入员工数量" :min="0" style="width: 100%" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item field="master_name" label="负责人姓名">
                            <a-input v-model="formData.master_name" placeholder="请输入负责人姓名" />
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row :gutter="16">
                    <a-col :span="12">
                        <a-form-item field="master_phone" label="负责人手机号" :rules="[
                            { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式' }
                        ]">
                            <a-input v-model="formData.master_phone" placeholder="请输入负责人手机号" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item field="address" label="地址">
                            <a-input v-model="formData.address" placeholder="请输入地址" />
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row :gutter="16">
                    <a-col :span="24">
                        <a-form-item field="remark" label="备注">
                            <a-textarea v-model="formData.remark" placeholder="请输入备注信息" :rows="3" />
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </a-modal>

        <a-modal v-model:visible="mastersVisible" draggable title="账号管理" 
            @cancel="closeModal" :width="800">
            <template #footer>
                <a-button type="primary" @click="handleAddMaster">
                    <template #icon><icon-plus /></template>
                    添加账号
                </a-button>
            </template>
            <div>
                <a-table :data="masterList">
                    <template #columns>
                        <a-table-column title="ID" data-index="id" :width="80" />
                        <a-table-column title="手机号" data-index="user.phone" :width="150"/>
                        <a-table-column title="姓名" data-index="user.nickname" :width="150"/>
                        <a-table-column title="创建时间" data-index="created_at" :width="180" />
                        <a-table-column title="操作" align="center" :width="280" fixed="right">
                            <template #cell="{ record }">
                                <a-space size="mini">

                                    
                                    <a-popconfirm position="left" content="确定要删除这个账号吗？" @ok="handleDeleteMaster(record.id)">
                                        <a-link>
                                            删除
                                        </a-link>
                                    </a-popconfirm>

                                </a-space>
                            </template>
                        </a-table-column>
                    </template>
                </a-table>
            </div>
        </a-modal>

        <a-modal draggable v-model:visible="addMasterModalVisible" title="添加账号" @before-ok="handleAddMasterSubmit"
            @cancel="closeAddMasterModal" :width="400">
            <a-form :model="masterFormData" ref="masterFormRef" layout="vertical">
                <a-form-item field="user_id" label="用户ID">
                    <a-input v-model="masterFormData.user_id" placeholder="请输入用户ID" />
                </a-form-item>
            </a-form>
        </a-modal>

        <!-- 单位客服管理抽屉 -->
        <a-drawer v-model:visible="kfModalVisible" title="单位客服管理" :width="800" placement="right">
            <template #footer>
                <a-button type="primary" @click="openKfFormModal()">
                    <template #icon><icon-plus /></template>
                    添加客服
                </a-button>
            </template>
            
            <a-table :data="kfList" :loading="kfLoading" :bordered="{ cell: true }" :pagination="kfPagination"
                @page-change="onKfPageChange" @page-size-change="onKfPageSizeChange" :scroll="{ x: 830 }">
                <template #columns>
                    <a-table-column title="ID" data-index="id" :width="80" />
                    <a-table-column title="客服姓名" data-index="realname" :width="120" />
                    <a-table-column title="联系电话" data-index="phone" :width="150" />
                    <a-table-column title="状态" data-index="status" :width="100">
                        <template #cell="{ record }">
                            <a-tag :color="record.status === 1 ? 'green' : 'red'">
                                {{ record.status === 1 ? '正常' : '禁用' }}
                            </a-tag>
                        </template>
                    </a-table-column>
                    <a-table-column title="服务公司" data-index="company_list" :width="200">
                        <template #cell="{ record }">
                            <a-space wrap>
                                <a-tag v-for="company in record.company_list" :key="company.id" color="blue">
                                    {{ company.name }}
                                </a-tag>
                                <span v-if="record.company_list.length === 0" style="color: #999;">暂无</span>
                            </a-space>
                        </template>
                    </a-table-column>
                    <a-table-column title="创建时间" data-index="created_at" :width="180" />
                    <a-table-column title="操作" align="center" :width="120" fixed="right">
                        <template #cell="{ record }">
                            <a-space size="mini">
                                <a-link @click="openKfFormModal(record)">
                                    编辑
                                </a-link>
                                <a-popconfirm position="left" content="确定要删除这个客服吗？" @ok="handleDeleteKf(record.id)">
                                    <a-link>
                                        删除
                                    </a-link>
                                </a-popconfirm>
                            </a-space>
                        </template>
                    </a-table-column>
                </template>
            </a-table>
        </a-drawer>

        <!-- 客服表单模态框 -->
        <a-modal v-model:visible="kfFormModalVisible" :title="kfFormData.id ? '编辑客服' : '添加客服'" @before-ok="handleKfSubmit"
            @cancel="closeKfFormModal" :width="750">
            <a-form :model="kfFormData" ref="kfFormRef" layout="vertical">
                <a-row :gutter="16">
                    <a-col :span="8">
                        <a-form-item field="realname" label="客服姓名" :rules="[{ required: true, message: '请输入客服姓名' }]">
                            <a-input v-model="kfFormData.realname" placeholder="请输入客服姓名" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="8">
                        <a-form-item field="phone" label="联系电话" :rules="[
                            { required: true, message: '请输入联系电话' },
                            { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式' }
                        ]">
                            <a-input v-model="kfFormData.phone" placeholder="请输入联系电话" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="8">
                        <a-form-item field="status" label="状态">
                            <a-select v-model="kfFormData.status" placeholder="请选择状态">
                                <a-option :value="1">正常</a-option>
                                <a-option :value="0">禁用</a-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-form-item field="company_ids" label="服务公司">
                    <a-select v-model="kfFormData.company_ids" placeholder="请选择服务公司" multiple allow-clear>
                        <a-option v-for="company in allCompanyList" :key="company.id" :value="company.id">
                            {{ company.name }}
                        </a-option>
                    </a-select>
                </a-form-item>
            </a-form>
        </a-modal>


    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { Message } from '@arco-design/web-vue';
import useLoading from '@/hooks/loading';
import { Pagination } from '@/types/global';
import { queryCompanyList, submitCompanyForm, delCompany, queryCityList, CompanyRecord, CompanyModel, CityOption, queryAllCompanyList, queryCompanyKfList, submitCompanyKfForm, delCompanyKf, CompanyKfRecord, CompanyKfModel, CompanyKfParams } from '@/api/company';
import { queryCompanyMasterList ,addCompanyMaster,deleteCompanyMaster} from '@/api/companyMaster';

const { loading, setLoading } = useLoading(true);
const modalVisible = ref(false);
const formRef = ref();
const cityLoading = ref(false);
const cityOptions = ref<CityOption[]>([]);

const basePagination = {
    current: 1,
    pageSize: 10,
    total: 0,
};

const pagination = reactive({
    ...basePagination,
});

const generateFormData = () => {
    return {
        id: 0,
        name: '',
        city_id: null,
        person_total: 0,
        master_name: '',
        master_phone: '',
        address: '',
        remark: '',
    };
};

const formData = ref(generateFormData());

const renderData = ref<CompanyRecord[]>([]);

const fetchData = async () => {
    setLoading(true);
    try {
        const res = await queryCompanyList({
            page: pagination.current,
            pageSize: pagination.pageSize,
        });
        renderData.value = res.data.list;
        pagination.total = res.data.total;
    } catch (err) {
        Message.error('获取公司列表失败');
    } finally {
        setLoading(false);
    }
};

const fetchCityOptions = async () => {
    cityLoading.value = true;
    try {
        const res = await queryCityList();
        cityOptions.value = res.data;
    } catch (err) {
        Message.error('获取城市列表失败');
    } finally {
        cityLoading.value = false;
    }
};

const onPageChange = (current: number) => {
    pagination.current = current;
    fetchData();
};

const onPageSizeChange = (pageSize: number) => {
    pagination.pageSize = pageSize;
    pagination.current = 1;
    fetchData();
};

const openModal = (record?: CompanyRecord) => {
    if (record) {
        formData.value = {
            id: record.id,
            name: record.name,
            city_id: record.city_id,
            person_total: record.person_total,
            master_name: record.master_name,
            master_phone: record.master_phone,
            address: record.address,
            remark: record.remark,
        };
    } else {
        formData.value = generateFormData();
    }
    modalVisible.value = true;
};

const closeModal = () => {
    modalVisible.value = false;
    formData.value = generateFormData();
};

const handleSubmit = async (done: any) => {
    setLoading(true);
    try {
        const res = await submitCompanyForm(formData.value);
        Message.success(res.msg || '操作成功');
        closeModal();
        fetchData();
        done(true);
    } catch (err) {
        done(false);
    } finally {
        setLoading(false);
    }
};

const handleDelete = async (id: number) => {
    try {
        await delCompany(id);
        Message.success('删除成功');
        fetchData();
    } catch (err) {
        Message.error('删除失败');
    }
};

const currentCompanyId = ref(0);
const masterFormData = ref({
    company_id: 0,
    user_id: 0,
});
const addMasterModalVisible = ref(false);
const handleAddMaster = () => {
    addMasterModalVisible.value = true;
    masterFormData.value.company_id = currentCompanyId.value;
};
const handleAddMasterSubmit = async (done:any) => {
    setLoading(true);
    try {
        const res = await addCompanyMaster(masterFormData.value);
        Message.success(res.msg || '操作成功');
        closeAddMasterModal();
        fetchMasterList(currentCompanyId.value);
        done(true);
    } catch (err) {
        done(false);
    } finally {
        setLoading(false);
    }
};

const closeAddMasterModal = () => {
    addMasterModalVisible.value = false;
    masterFormData.value = {
        company_id: 0,
        user_id: 0,
    };
};

const masterList = ref([]);
const fetchMasterList = async (companyId: number) => {
    const res = await queryCompanyMasterList(companyId);
    masterList.value = res.data;
};

const mastersVisible = ref(false);
const handleMasterData = (record: CompanyRecord) => {
    mastersVisible.value = true;
    currentCompanyId.value = record.id;
    fetchMasterList(record.id);
};

const handleDeleteMaster = async (id: number) => {
    try {
        await deleteCompanyMaster(id);
        Message.success('删除成功');
        fetchMasterList(currentCompanyId.value);
    } catch (err) {
        Message.error('删除失败');
    }
};

const kfModalVisible = ref(false);
const openKfModal = () => {
    kfModalVisible.value = true;
    fetchKfData();
};

// 客服列表相关
const kfLoading = ref(false);
const kfList = ref<CompanyKfRecord[]>([]);
const kfPagination = reactive({
    current: 1,
    pageSize: 10,
    total: 0,
});

const fetchKfData = async () => {
    kfLoading.value = true;
    try {
        const res = await queryCompanyKfList({
            page: kfPagination.current,
            pageSize: kfPagination.pageSize,
        });
        kfList.value = res.data.list;
        kfPagination.total = res.data.total;
    } catch (err) {
        Message.error('获取客服列表失败');
    } finally {
        kfLoading.value = false;
    }
};

const onKfPageChange = (current: number) => {
    kfPagination.current = current;
    fetchKfData();
};

const onKfPageSizeChange = (pageSize: number) => {
    kfPagination.pageSize = pageSize;
    kfPagination.current = 1;
    fetchKfData();
};

// 客服表单相关
const kfFormModalVisible = ref(false);
const kfFormRef = ref();
const kfFormData = ref<CompanyKfModel>({
    id: 0,
    realname: '',
    phone: '',
    company_ids: [],
    status: 1,
});

const openKfFormModal = (record?: CompanyKfRecord) => {
    if (record) {
        // 解析公司IDs
        let companyIds: number[] = [];
        if (record.company_ids) {
            companyIds = record.company_ids.split('@').filter(id => id !== '').map(id => parseInt(id, 10));
        }
        
        kfFormData.value = {
            id: record.id,
            realname: record.realname,
            phone: record.phone,
            company_ids: companyIds,
            status: record.status,
        };
    } else {
        kfFormData.value = {
            id: 0,
            realname: '',
            phone: '',
            company_ids: [],
            status: 1,
        };
    }
    kfFormModalVisible.value = true;
};

const closeKfFormModal = () => {
    kfFormModalVisible.value = false;
    kfFormData.value = {
        id: 0,
        realname: '',
        phone: '',
        company_ids: [],
        status: 1,
    };
};

const handleKfSubmit = async (done: any) => {
    kfLoading.value = true;
    try {
        const res = await submitCompanyKfForm(kfFormData.value);
        Message.success(res.msg || '操作成功');
        closeKfFormModal();
        fetchKfData();
        done(true);
    } catch (err) {
        done(false);
    } finally {
        kfLoading.value = false;
    }
};

const handleDeleteKf = async (id: number) => {
    try {
        await delCompanyKf(id);
        Message.success('删除成功');
        fetchKfData();
    } catch (err) {
        Message.error('删除失败');
    }
};



// 获取所有公司列表（用于选择）
const allCompanyList = ref<CompanyRecord[]>([]);
const fetchAllCompanyList = async () => {
    try {
        const res = await queryAllCompanyList();
        allCompanyList.value = res.data;
    } catch (err) {
        Message.error('获取公司列表失败');
    }
};

onMounted(() => {
    fetchData();
    fetchCityOptions();
    fetchAllCompanyList();
});
</script>

<style scoped lang="less">
.container {
    padding: 0 20px 20px 20px;
}
</style>

<script lang="ts">
export default {
    name: 'MemberCompany',
};
</script>
